package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("setmeal")
public class SetmealMobileController {

    @Autowired
    JedisPool jedisPool;


    @Reference
    private SetmealService setmealService;

    @RequestMapping("findAll")
    public Result findAll(){

        try {
            String setmealList = jedisPool.getResource().get(RedisMessageConstant.SETMEAL_LIST);
            if (setmealList==null){
                List<Setmeal> list = setmealService.findAll();
                setmealList = JSON.toJSONString(list);
                jedisPool.getResource().set(RedisMessageConstant.SETMEAL_LIST,setmealList);
            }
            List<Setmeal> list = JSON.parseArray(setmealList, Setmeal.class);
            return new Result(true, MessageConstant.QUERY_SETMEALLIST_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEALLIST_FAIL);
        }

    }

    /**
     * 通过id查询套餐、检查组和检查项
     */
    @RequestMapping("findById")
    public Result findById(@RequestParam("id")Integer id){

        try {
            String setmealDetail = jedisPool.getResource().get(id + RedisMessageConstant.SETMEAL_DETAIL);
            if (setmealDetail==null){
                Setmeal setmeal = setmealService.findById(id);
                setmealDetail = JSON.toJSONString(setmeal);
                jedisPool.getResource().set(id + RedisMessageConstant.SETMEAL_DETAIL,setmealDetail);
            }
            Setmeal setmeal = JSON.parseObject(setmealDetail, Setmeal.class);
            return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

}
